package com.pisolution.scheduler.datasource.instance;

import com.baomidou.mybatisplus.annotation.EnumValue;

import javax.annotation.Nullable;

/**
 * 工作流与任务节点的运行状态.
 *
 * @author sora
 * @version 0.1.0
 */
public enum ExecutionState {
    /** 提交成功. */
    SUBMITTED_SUCCESS(0),

    /** 正在运行. */
    RUNNING(1),

    /** 准备暂停. */
    READY_PAUSE(2),

    /** 暂停. */
    PAUSE(3),

    /** 准备停止. */
    READY_STOP(4),

    /** 停止. */
    STOP(5),

    /** 失败. */
    FAILURE(6),

    /** 成功. */
    SUCCESS(7),

    /** 需要容错. */
    NEED_FAULT_TOLERANCE(8),

    /** 死亡. */
    KILL(9),

    /** 等待线程. */
    WAITING_THREAD(10),

    /** 等待依赖. */
    WAITING_DEPEND(11);

    // -------------------------------------------------------------------------------------------------

    /** 当前运行状态在集合中的序号. */
    @EnumValue
    private final int code;

    // -------------------------------------------------------------------------------------------------
    //  初始化
    // -------------------------------------------------------------------------------------------------

    ExecutionState(final int code) {
        this.code = code;
    }

    // -------------------------------------------------------------------------------------------------
    //  属性访问
    // -------------------------------------------------------------------------------------------------

    public int getCode() {
        return this.code;
    }

    // -------------------------------------------------------------------------------------------------
    //  状态转换
    // -------------------------------------------------------------------------------------------------

    /**
     * 将给定的运行状态码转换为 {@link ExecutionState} 对象.
     *
     * @param code 待转换运行状态码.
     *
     * @return 转换后的 {@link ExecutionState} 对象.
     */
    @Nullable
    public static ExecutionState of(final int code) {
        for (final ExecutionState state: values()) {
            if (state.code == code) {
                return state;
            }
        }

        return null;
    }

    // -------------------------------------------------------------------------------------------------
    //  状态分类
    // -------------------------------------------------------------------------------------------------

    /**
     * 确认当前状态是否为完成状态.
     *
     * @return 如果是完成状态 则返回 {@code true} 否则返回 {@code false}.
     */
    public boolean isFinished() {
        return this == SUCCESS
            || this == FAILURE
            || this == NEED_FAULT_TOLERANCE
            || this == KILL
            || this == STOP
            || this == PAUSE;
    }
}
